import { type App } from 'vue'
import { useSocketStore } from '@/store/useSocketStore'

export function createSocketPlugin() {
    return {
        install(app: App) {
            const socketStore = useSocketStore()

            // 初始化 socket 连接
            socketStore.initSocket()

            // 添加全局属性
            app.config.globalProperties.$socket = {
                emit: socketStore.emit,
                on: socketStore.on,
                off: socketStore.off,
            }

            // 页面可见性变化时的处理
            document.addEventListener('visibilitychange', () => {
                if (document.visibilityState === 'visible') {
                    if (!socketStore.isConnected) {
                        socketStore.connect()
                    }
                }
            })

            // 在线状态检测
            window.addEventListener('online', () => {
                socketStore.connect()
            })

            window.addEventListener('offline', () => {
                socketStore.disconnect()
            })
        }
    }
}